package com.example.huadu_server.landlord.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.example.huadu_server.appointment.dto.AppointmentAuditDTO;
import com.example.huadu_server.appointment.service.AppointmentService;
import com.example.huadu_server.config.Response;
import com.example.huadu_server.house.dto.HouseUploadDTO;
import com.example.huadu_server.house.dto.UpdateHouseStatusDTO;
import com.example.huadu_server.house.entity.House;
import com.example.huadu_server.house.service.HouseService;
import com.example.huadu_server.landlord.dto.*;
import com.example.huadu_server.landlord.entity.Landlord;
import com.example.huadu_server.landlord.entity.LandlordSchedule;
import com.example.huadu_server.landlord.service.LandlordScheduleService;
import com.example.huadu_server.landlord.service.LandlordService;
import com.example.huadu_server.oss.service.OssService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.*;

@RestController
@RequestMapping("/landlord")
public class LandlordController {

    @Autowired
    private LandlordService landlordService;

    @Autowired
    private LandlordScheduleService landlordScheduleService;

    /**
     * 修改密码
     */
    @PostMapping("/modifyPass")
    public Response<String> modifyPassword(@RequestBody @Valid ModifyPasswordDTO modifyPasswordDTO) {
        int landlordId = StpUtil.getLoginIdAsInt();
        return landlordService.modifyPassword(
                landlordId,
                modifyPasswordDTO.getOldPassword(),
                modifyPasswordDTO.getNewPassword(),
                modifyPasswordDTO.getConfirmPassword()
        );
    }

    /**
     * 获取验证码 (GET)
     */
    @GetMapping("/forgetPassCode")
    public ResponseEntity<Response<String>> sendForgetPasswordCode(@RequestParam String email) {
        Response<String> response = landlordService.sendForgetPasswordCode(email);
        return ResponseEntity.status(response.getCode()).body(response);
    }

    /**
     * 重置密码 (POST)
     */
    @PostMapping("/forgetPass")
    public Response<String> resetPassword(@RequestBody @Valid ForgetPasswordDTO forgetPasswordDTO) {
        return landlordService.resetPassword(
                forgetPasswordDTO.getEmail(),
                forgetPasswordDTO.getCode(),
                forgetPasswordDTO.getNewPassword(),
                forgetPasswordDTO.getConfirmPassword()
        );
    }

    /**
     * 获取用户个人信息
     *
     * @return ResponseEntity<Response < User>>
     */
    @GetMapping("/userInfo")
    public ResponseEntity<Response<Landlord>> getUserInfo() {
        // 获取当前登录用户的 ID
        int landlordId = StpUtil.getLoginIdAsInt();

        // 调用 Service 层获取用户信息
        Response<Landlord> response = landlordService.getLandlordInfoById(landlordId);

        return ResponseEntity.status(response.getCode()).body(response);
    }

    /**
     * 修改用户个人信息
     */
    @PostMapping("/updateInfo")
    public Response<String> updateUserInfo(@RequestBody UpdateInfoDTO updateInfoDTO) {
        int landlordId = StpUtil.getLoginIdAsInt(); // 获取当前登录用户的 ID
        return landlordService.updateLandlordInfo(landlordId, updateInfoDTO);
    }

    /**
     * 获取修改邮箱验证码
     */
    @GetMapping("/getUpdateEmailCode")
    public Response<String> sendUpdateEmailCode(@RequestParam String email) {
        return landlordService.sendUpdateEmailCode(email);
    }

    /**
     * 修改用户邮箱
     */
    @PostMapping("/updateEmail")
    public Response<String> updateUserEmail(@RequestBody @Valid LandlordInfoDTO landlordInfoDTO) {
        int landlordId = StpUtil.getLoginIdAsInt(); // 获取当前登录用户的 ID
        return landlordService.updateUserEmail(landlordId, landlordInfoDTO);
    }

    /**
     * 上传用户头像
     */
    @PostMapping("/uploadLogo")
    public Response<String> uploadUserLogo(@RequestParam("file") MultipartFile file) {
        int landlordId = StpUtil.getLoginIdAsInt(); // 获取当前登录用户 ID
        // 检查是否上传文件---哪怕没有上传图片也会有默认值，所以先排除掉默认值再进行判断是否上传文件
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null || originalFilename.isEmpty() ||
                originalFilename.startsWith("1735872250277_")) {
            return new Response<>(400, "请上传图片", null);
        }
        return landlordService.uploadLandlordLogo(file, landlordId);
    }

    @Autowired
    private OssService ossService;

    /**
     * 房东上传多张房源图片
     *
     * @param files 图片文件数组
     * @return 图片 URL 列表
     */
    @PostMapping("/uploadImage")
    public Response<List<String>> uploadHouseImages(@RequestParam("file") MultipartFile[] files) {
        List<String> imageUrls = new ArrayList<>();
        try {
            for (MultipartFile file : files) {
                // 检查是否上传文件---哪怕没有上传图片也会有默认值，所以先排除掉默认值再进行判断是否上传文件
                String originalFilename = file.getOriginalFilename();
                if (originalFilename == null || originalFilename.isEmpty() ||
                        originalFilename.startsWith("1735872250277_")) {
                    return new Response<>(400, "请上传有效的图片", null);
                }

                String url = ossService.uploadFile(file, "houses"); // 上传到七牛云
                if (url != null) {
                    imageUrls.add(url);
                } else {
                    return new Response<>(500, "部分图片上传失败", null);
                }
            }
            return new Response<>(200, "上传成功", imageUrls);
        } catch (Exception e) {
            return new Response<>(500, "图片上传失败：" + e.getMessage(), null);
        }
    }


    /**
     * 上传房源产权证明
     */
    @PostMapping("/uploadTitleDeed")
    public Response<List<Map<String, Object>>> uploadTitleDeed(@RequestParam("file") MultipartFile[] files) {
        List<Map<String, Object>> fileDetails = new ArrayList<>();
        try {
            for (MultipartFile file : files) {
                // 检查是否上传文件
                String originalFilename = file.getOriginalFilename();
                if (originalFilename == null || originalFilename.isEmpty() ||
                        originalFilename.startsWith("1735872250277_")) {
                    return new Response<>(400, "请上传有效的图片", null);
                }

                String url = ossService.uploadFile(file, "HouseTitleDeed"); // 上传到七牛云
                if (url != null) {
                    // 获取文件类型
                    String fileType = file.getContentType();

                    // 将文件 URL 和类型添加到返回数据中
                    Map<String, Object> fileDetail = new HashMap<>();
                    fileDetail.put("url", url);
                    fileDetail.put("fileType", fileType);

                    fileDetails.add(fileDetail);
                } else {
                    return new Response<>(500, "部分图片上传失败", null);
                }
            }
            return new Response<>(200, "上传成功", fileDetails);
        } catch (Exception e) {
            return new Response<>(500, "图片上传失败：" + e.getMessage(), null);
        }
    }


    @Autowired
    private HouseService houseService;

    /**
     * 房源提交接口
     *
     * @param houseUploadDTO 房源信息
     * @return 上传结果
     */
    @PostMapping("/uploadHouse")
    public Response<String> uploadHouse(@RequestBody HouseUploadDTO houseUploadDTO) {
        int landlordId = StpUtil.getLoginIdAsInt(); // 获取当前房东 ID
        return houseService.uploadHouse(houseUploadDTO, landlordId);
    }

    /**
     * 根据房源的房东ID获取房东信息
     *
     * @param houseId 房源ID
     * @return
     */
    @GetMapping("/getLandlordByHouseId/{houseId}")
    public Response<Landlord> getLandlordByHouseId(@PathVariable("houseId") int houseId) {
        return houseService.getLandlordByHouseId(houseId);
    }

    @Autowired
    private AppointmentService appointmentService;

    /**
     * 获取房东的预约记录
     *
     * @param status
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("/allAppointments/{pageNo}/{pageSize}")
    public Response<Map<String, Object>> getAppointmentsByLandlordId(
            @PathVariable int pageNo,
            @PathVariable int pageSize,
            @RequestParam(required = false) String status) {
        // 使用 Sa-Token 校验登录状态
        StpUtil.checkLogin();
        // 通过 Sa-Token 获取当前登录用户的 ID
        int landlordId = StpUtil.getLoginIdAsInt();
        return appointmentService.getAppointmentsByLandlordId(landlordId, status, pageNo, pageSize);
    }

    /**
     * 审核预约
     *
     * @param appointmentAuditDTO
     * @return
     */
    @PostMapping("/auditAppointment")
    public ResponseEntity<Response<String>> auditAppointment(@RequestBody AppointmentAuditDTO appointmentAuditDTO) {
        // 校验登录状态
        StpUtil.checkLogin();
        int currentLandlordId = StpUtil.getLoginIdAsInt();
        // 直接把当前房东ID传给 Service
        Response<String> result = appointmentService.auditAppointment(currentLandlordId, appointmentAuditDTO);
        return ResponseEntity.status(result.getCode()).body(result);
    }


    /**
     * 通过房源 ID 查询房源详细信息
     *
     * @param houseId 房源 ID
     * @return 房源详细信息
     */
    @GetMapping("/getHouseById/{houseId}")
    public ResponseEntity<Response<House>> getHouseById(@PathVariable("houseId") int houseId) {
        Response<House> result = houseService.getHouseByIdLandlord(houseId);
        return ResponseEntity.status(result.getCode()).body(result);
    }

    /**
     * 房东获取自己的房源列表
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("/myHouses/{pageNo}/{pageSize}/{status}")
    public ResponseEntity<Response<Map<String, Object>>> getHousesByLandlordId(
            @PathVariable int pageNo,
            @PathVariable int pageSize,
            @PathVariable String status) {
        // 校验登录状态
        StpUtil.checkLogin();
        int currentLandlordId = StpUtil.getLoginIdAsInt();
        // 调用房源服务接口，根据房东ID分页查询房源信息
        Response<Map<String, Object>> result = houseService.getHousesByLandlordId(currentLandlordId, pageNo, pageSize,status);
        return ResponseEntity.status(result.getCode()).body(result);
    }

    /**
     * 更新房源信息
     *
     * @param house
     * @return
     */
    @PostMapping("/updateHouse")
    public ResponseEntity<Response<String>> updateHouse(@RequestBody House house) {
        // 校验登录状态（例如使用 Sa-Token）
        StpUtil.checkLogin();
        // 你可以根据需求设置当前登录的房东ID到 house 对象中，
        // 比如：house.setLandlordId(StpUtil.getLoginIdAsInt());
        Response<String> result = houseService.updateHouse(house);
        return ResponseEntity.status(result.getCode()).body(result);
    }

    /**
     * 更新房源状态
     *
     * @param updateHouseStatusDTO
     * @return
     */
    @PostMapping("/updateHouseStatus")
    public ResponseEntity<Response<String>> updateHouseStatus(@RequestBody UpdateHouseStatusDTO updateHouseStatusDTO) {
        if (updateHouseStatusDTO.getHouseId() == null || updateHouseStatusDTO.getNewStatus() == null) {
            return ResponseEntity.badRequest().body(new Response<>(400, "参数错误", null));
        }
        Response<String> result = houseService.updateHouseStatus(updateHouseStatusDTO.getHouseId(), updateHouseStatusDTO.getNewStatus());
        return ResponseEntity.status(result.getCode()).body(result);
    }


    /**
     * 获取房东未来七天的档期信息，并在查询时自动初始化档期数据（如果数据库中没有数据）
     */
    @GetMapping("/landlordSchedules")
    public ResponseEntity<Response<List<LandlordSchedule>>> getLandlordSchedules() {
        StpUtil.checkLogin();
        int landlordId = StpUtil.getLoginIdAsInt();

        // 从明天开始
        Calendar calStart = Calendar.getInstance();
        calStart.add(Calendar.DAY_OF_MONTH, 1);
        Date startDate = calStart.getTime();

        // 往后 6 天，总共 7 天
        calStart.add(Calendar.DAY_OF_MONTH, 6);
        Date endDate = calStart.getTime();

        // 调用服务
        List<LandlordSchedule> schedules =
                landlordScheduleService.getSchedulesForLandlord(landlordId, startDate, endDate);

        return ResponseEntity.ok(new Response<>(200, "查询成功", schedules));
    }

    /**
     * 房东获取所有档期信息
     * @param status
     * @param isFuture
     * @return
     */
    @GetMapping("/myAllSchedules")
    public ResponseEntity<Response<Map<String, Object>>> getLandlordSchedules(
            @RequestParam(value = "status", required = false) String status,  // 状态筛选
            @RequestParam(value = "isFuture", defaultValue = "true") boolean isFuture) {  // 是否仅查询未来档期

        // 获取当前登录房东的 ID
        StpUtil.checkLogin();
        int landlordId = StpUtil.getLoginIdAsInt();

        // 调用 service 获取房东的档期数据
        Response<Map<String, Object>> response = landlordScheduleService.getLandlordSchedules(
                landlordId, status, isFuture);

        // 返回响应
        return ResponseEntity.status(response.getCode()).body(response);
    }

    /**
     * 房东更新档期状态
     */
    @PostMapping("/updateSchedule")
    public ResponseEntity<Response<String>> updateSchedule(@RequestBody @Valid UpdateScheduleDTO updateScheduleDTO) {
        StpUtil.checkLogin();
        int landlordId = StpUtil.getLoginIdAsInt();

        Response<String> result = landlordScheduleService.updateScheduleStatus(
                updateScheduleDTO.getScheduleId(),
                updateScheduleDTO.getNewStatus(),
                landlordId,
                updateScheduleDTO.getReason()
        );
        return ResponseEntity.status(result.getCode()).body(result);
    }

}
